<template>
  <div class="com-container">
    <div class="com-chart" id="stock"></div>
  </div>
</template>

<script setup>
import {onMounted, onBeforeUnmount, inject, reactive, ref, watch} from "vue";
import { useStore } from 'vuex'
import { getStockData } from "@/service/getChartsData";

// 1. 接收Echarts
let echarts = inject('echarts')
let chartInstance = reactive({})

// 2. 定义接收数据变量
let chartDate = reactive([])
let seriesArr = reactive([])
let start = ref(0)
let end = ref(5)
let titleFontSize = ref(null)
let timer = reactive({})
const store = useStore()

async function getChartData() {
  let {data: res} = await getStockData()
  chartDate = res
}

function initChart() {
  chartInstance = echarts.init(document.querySelector("#stock"), store.state.theme)

  const initOption = {
    title: {
      text: '▎库存和销量分析',
      left: 20,
      top: 20
    }
  }

  chartInstance.setOption(initOption)

}

function setChartData(){
  const centerArr = [
    ['18%', '40%'],
    ['50%', '40%'],
    ['82%', '40%'],
    ['34%', '75%'],
    ['66%', '75%']
  ]

  const colorArr = [
    ['#4FF778', '#0BA82C'],
    ['#E5DD45', '#E8B11C'],
    ['#E8821C', '#E55445'],
    ['#5052EE', '#AB6EE5'],
    ['#23E5E5', '#2E72BF']
  ]

  let showData = chartDate.slice(start.value, end.value)

  seriesArr = showData.map((item, index) => {
    return {
      type:'pie', // 表为饼图
      center: centerArr[index], // 定位, [水平，垂直]
      hoverAnimation: false, // 是否关闭鼠标移入饼图时的动画效果
      // 指示线样式
      labelLine: {
        show: false // 隐藏指示线
      },
      // 内容样式
      label: {
        position: 'center', // 内容居中于园内
        color: colorArr[index][0]
      },
      data:[
        {
          name: item.name + '\n\n' + item.sales, // 圆内数据
          value: item.sales, // 圆边框数据
          // 圆环颜色设置
          itemStyle:{
            color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
              {
                offset:0,
                color:colorArr[index][0]
              },
              {
                offset:1,
                color:colorArr[index][1]
              }
            ])

          }
        },
        {
          value: item.stock, // 圆边框数据
          // 圆环颜色设置
          itemStyle:{
            color:'#333843'
          }
        }
      ]
    }

  })

}

function updateChart() {
  setChartData()
  const updateOption = {
    series:seriesArr
  }
  chartInstance.setOption(updateOption)
}

function startInterval() {
  if (timer) clearInterval(timer)

  timer = setInterval(() => {
    start.value += 5
    end.value += 5
    if(end.value > chartDate.length ){
      start.value = 0
      end.value = 5
    }
    updateChart()
  },3000)
}

function eventListeners() {
  chartInstance.on('mouseover', () => {
     clearInterval(timer)
  })
  chartInstance.on('mouseout', () => {
    startInterval()
  })
}

function screenAdapter() {
  titleFontSize.value = document.querySelector("#stock").offsetWidth / 100 * 3.6
  const innerRadius = titleFontSize.value * 3
  const outerRadius = innerRadius * 1.125
  const adapterOption = {
    title:{
      textStyle: {
        fontSize: titleFontSize.value
      }
    },
    series:[
      {
        type: 'pie',
        radius: [outerRadius, innerRadius],// // [外圆半径，内圆半径]
        label:{
          fontSize: titleFontSize.value / 1.5 //圆内字体大小
        }
      },
      {
        type: 'pie',
        radius: [outerRadius, innerRadius], // 外圆半径，内圆半径
        label:{
          fontSize: titleFontSize.value / 1.5
        }
      },
      {
        type: 'pie',
        radius: [outerRadius, innerRadius],
        label:{
          fontSize: titleFontSize.value / 1.5
        }
      },
      {
        type: 'pie',
        radius: [outerRadius, innerRadius],
        label:{
          fontSize: titleFontSize.value / 1.5
        }
      },
      {
        type: 'pie',
        radius: [outerRadius, innerRadius],
        label:{
          fontSize: titleFontSize.value / 1.5
        }
      }
    ]

  }
  chartInstance.setOption(adapterOption)
  chartInstance.resize()
}

watch(() => store.state.theme, () => {
  chartInstance.dispose()//销毁当前的图表
  initChart()//重新初始化图表对象
  updateChart()//更新图表的展示
  screenAdapter()//完成屏幕的适配
})

onMounted(() => {
   getChartData().then(() => {
     initChart()
     updateChart()
     startInterval()
     eventListeners()
     screenAdapter()
   })
  window.addEventListener('resize',screenAdapter)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize',screenAdapter)
  clearInterval(timer)
})

// 导出 适配函数 以便父组件screenPage使用
defineExpose ({
  screenAdapter
})

</script>

<style scoped>

</style>